<template>
  <el-drawer
    v-model="drawerVisible"
    :destroy-on-close="true"
    size="450px"
    :title="`${drawerProps.title}字典${drawerProps.row!.parentId ? '项' : ''}`"
  >
    <el-form
      ref="ruleFormRef"
      label-width="130px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item :label="dictName" prop="name">
        <el-input v-model="drawerProps.row!.name" placeholder="请填写字典名称" clearable></el-input>
      </el-form-item>
      <el-form-item :label="`${dictName}(英文)`" prop="nameEn">
        <el-input v-model="drawerProps.row!.nameEn" placeholder="请填写字典英文名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="值" prop="value">
        <el-input v-model="drawerProps.row!.value" placeholder="请填写值" clearable></el-input>
      </el-form-item>
      <el-form-item label="图标" prop="icon" v-show="drawerProps.row!.parentId">
        <UploadImg v-model:image-url="drawerProps.row!.icon" width="135px" height="135px" :file-size="3">
          <template #empty>
            <el-icon><Avatar /></el-icon>
            <span>请上传图标</span>
          </template>
          <template #tip> 图标大小不能超过 3M </template>
        </UploadImg>
      </el-form-item>
      <el-form-item label="数据类型" prop="type">
        <el-select v-model="drawerProps.row!.type" placeholder="请选择" clearable>
          <el-option v-for="item in dictValueType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item
        label="选择器类型"
        prop="param"
        v-show="
          dictValueType
            .filter(item => item.isList)
            .map(item => item.value)
            .includes(drawerProps.row!.type)
        "
      >
        <el-select
          v-model="drawerProps.row!.param"
          placeholder="请选择"
          clearable
          filterable
          remote
          :remote-method="getSearchDictListFn"
          :loading="loading"
        >
          <el-option v-for="item in chooseList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="value">
        <el-input v-model="drawerProps.row!.sort" placeholder="请填写" clearable></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="drawerProps.row!.remark" placeholder="请填写备注" clearable></el-input>
      </el-form-item>
      <el-form-item v-show="drawerProps.isView" label="修改人" prop="modifiedBy">
        <el-input v-model="drawerProps.row!.modifiedBy" placeholder="请填写备注" clearable></el-input>
      </el-form-item>
      <el-form-item v-show="drawerProps.isView" label="修改时间" prop="gmtModified">
        <el-input v-model="drawerProps.row!.gmtModified" placeholder="" clearable></el-input>
      </el-form-item>
      <el-form-item v-show="drawerProps.isView" label="创建人" prop="createBy">
        <el-input v-model="drawerProps.row!.createBy" placeholder="" clearable></el-input>
      </el-form-item>
      <el-form-item v-show="drawerProps.isView" label="创建时间" prop="gmtCreate">
        <el-input v-model="drawerProps.row!.gmtCreate" placeholder="" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false"> 取消 </el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="DictDrawer">
import { ref, reactive, computed } from "vue";
import { dictValueType } from "@/utils/serviceDict";
import { ElMessage, FormInstance } from "element-plus";
import { Dict } from "@/api/interface";
import UploadImg from "@/components/Upload/Img.vue";
import { useDict } from "@/hooks/useDict";
// api
import { getSearchDictList, getDict } from "@/api/modules/sys";
// 变量
const { dict } = useDict();
const loading = ref(false);
let chooseList = ref([]);
const rules = reactive({
  name: [{ required: true, message: "请填写字典名称" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  type: number;
  row: Partial<Dict.ResDictList>;
  api?: (params: any) => Promise<any>;
  getTableList?: (params?: any) => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {},
  type: 0
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      let { data } = await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerProps.value.type === 3 || drawerProps.value.type === 2
        ? drawerProps.value.getTableList!(data)
        : drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};
// computed
const dictName = computed(() => {
  return drawerProps.value.row.parentId ? "字典项名称" : "字典名称";
});

// 方法
const getSearchDictListFn = async query => {
  loading.value = true;
  const { data } =
    drawerProps.value.row!.type === 3
      ? await getSearchDictList({ searchKey: query })
      : await getDict({ parentId: dict.accessoryType });
  loading.value = false;
  chooseList.value = data;
};
defineExpose({
  acceptParams
});
</script>
